#coding:utf-8
import scrapy
import json
import csvout

class QuotesSpider(scrapy.Spider):
    name = "bookask"

    def start_requests(self):
        url = 'http://www.bookask.com'
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + '/s/kw_' + tag;
            yield scrapy.Request(url + '/t_0.html', self.parse_book_num)
            yield scrapy.Request(url + '/t_4.html', self.parse_digital_book_num)

    def parse_book_num(self, response):
        res = response.xpath('//*[@id="headcmnaft"]/ol/li[3]/text()').extract_first()
        #unicode字符串，取出'到‘和’个'之间的数字
        num = res.split(u'到')[1].split(u'个')[0]
        num = int(num)
        outli = ['book_num', num, response.url]
        csvout.list2csv(outli)
        yield {
            'book_num': num
        }
    def parse_digital_book_num(self, response):
        res = response.xpath('//*[@id="headcmnaft"]/ol/li[3]/text()').extract_first()
        #unicode字符串，取出'到‘和’个'之间的数字
        num = res.split(u'到')[1].split(u'个')[0]
        num = int(num)
        outli = ['digital_book_num', num, response.url]
        csvout.list2csv(outli)
        yield {
            'digital_book_num': num
        }
